#!/usr/bin/env python
#  -*- coding: utf-8 -*-
__author__="ImFatFish"

import asyncio
import websockets
import json
import pymcwsapi
import time
from websockets import ConnectionClosedError

class MCWS():
    def __init__(self,ws_port=19133,
    ws_onstartserver=None,ws_onconnect=None,ws_ondisconnect=None,
    ws_onsubscribe=None,ws_onreceive=None):
        self._api=pymcwsapi.MCWSApi()
        self.ws_address="localhost"
        self.ws_port=ws_port
        self._ws_onstartserver=ws_onstartserver
        self._ws_onconnect=ws_onconnect
        self._ws_ondisconnect=ws_ondisconnect
        self.subscribe_list=self._api.get_subscribe_list()
        self._pkg_subscribe_list=self._api.get_pkg_subscribe(self.subscribe_list)
        self._ws_onsubscribe=ws_onsubscribe
        self._ws_onreceive=ws_onreceive
        self._ws_waittime=1
    def start_server(self):
        asyncio.get_event_loop().run_until_complete(websockets.serve(self._mainloop,self.ws_address,self.ws_port))
        if self._ws_onstartserver != None:self._ws_onstartserver()
        asyncio.get_event_loop().run_forever()
    async def _mainloop(self,ws,path):
        self._ws=ws
        time.sleep(self._ws_waittime)
        if self._ws_onconnect != None:await self._ws_onconnect()
        while True:
            try:
                await self._subscribe()
                await self._receive()
            except ConnectionClosedError:
                if self._ws_ondisconnect != None:await self._ws_ondisconnect()
                break
    async def _subscribe(self):
        for x in self._pkg_subscribe_list:await self._ws.send(x)
        if self._ws_onsubscribe != None:await self._ws_onsubscribe()
    async def _receive(self):
        recv_data=json.loads(str(await self._ws.recv()))
        if self._ws_onreceive != None:await self._ws_onreceive(recv_data)
    async def sendcommand(self,commandline):
        await self._ws.send(self._api.get_pkg_command(commandline))